package com.ruoyi.msg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.msg.domain.MsgDcwjTk;
import com.ruoyi.msg.domain.MsgDcwjTkXx;
import com.ruoyi.msg.domain.bo.MsgDcwjTkBo;
import com.ruoyi.msg.domain.bo.TkFormBo;
import com.ruoyi.msg.domain.vo.MsgDcwjTkVo;
import com.ruoyi.msg.domain.vo.TkXxDetailVo;
import com.ruoyi.msg.mapper.MsgDcwjTkMapper;
import com.ruoyi.msg.mapper.MsgDcwjTkXxMapper;
import com.ruoyi.msg.service.IMsgDcwjTkService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 题库管理Service业务层处理
 *
 * @author xiaohao
 * @date 2023-02-01
 */
@RequiredArgsConstructor
@Service
public class MsgDcwjTkServiceImpl implements IMsgDcwjTkService {

    private final MsgDcwjTkMapper baseMapper;
    private final MsgDcwjTkXxMapper tkXxMapper;

    @Override
    public TkXxDetailVo getDetail(Long id) {
        // 题库信息
        MsgDcwjTk tkInfo = baseMapper.selectById(id);
        TkXxDetailVo detailVo = BeanUtil.toBean(tkInfo, TkXxDetailVo.class);
        if (detailVo != null) {
            // 详情列表
            List<MsgDcwjTkXx> options = tkXxMapper.selectList(
                Wrappers.<MsgDcwjTkXx>lambdaQuery()
                    .eq(MsgDcwjTkXx::getTkId, id)
                    .orderByAsc(MsgDcwjTkXx::getSort)
            );
            List<TkXxDetailVo.OptionsDTO> optionsDTOList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(options)) {
                options.forEach(option -> optionsDTOList.add(BeanUtil.toBean(option, TkXxDetailVo.OptionsDTO.class)));
            }
            detailVo.setOptions(optionsDTOList);
        }
        return detailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateForm(TkFormBo bo) {
        MsgDcwjTkBo entity = BeanUtil.toBean(bo, MsgDcwjTkBo.class);
        if (bo.getId() == null) {
            // 新增题库信息
            this.insertByBo(entity);
            // 新增选项信息
            List<MsgDcwjTkXx> options = bo.getOptions();
            if (options != null) {
                // 绑定关系
                Long tkId = entity.getId();
                options.forEach(option -> option.setTkId(tkId)
                );
                tkXxMapper.insertBatch(options);
            }
        } else {
            // 更新题库信息
            this.updateByBo(entity);
            // 更新选项信息
            List<MsgDcwjTkXx> options = bo.getOptions();
            if (options != null) {
                // 绑定关系
                Long tkId = bo.getId();
                options.forEach(option -> option.setTkId(tkId)
                );
                tkXxMapper.insertOrUpdateBatch(options);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void relaDel(Long id) {
        baseMapper.deleteById(id);
        tkXxMapper.delete(
            Wrappers.<MsgDcwjTkXx>lambdaQuery()
                .eq(MsgDcwjTkXx::getTkId, id)
        );
    }

    /**
     * 查询题库管理
     */
    @Override
    public MsgDcwjTkVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询题库管理列表
     */
    @Override
    public TableDataInfo<MsgDcwjTkVo> queryPageList(MsgDcwjTkBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MsgDcwjTk> lqw = buildQueryWrapper(bo);
        Page<MsgDcwjTkVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询题库管理列表
     */
    @Override
    public List<MsgDcwjTkVo> queryList(MsgDcwjTkBo bo) {
        LambdaQueryWrapper<MsgDcwjTk> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MsgDcwjTk> buildQueryWrapper(MsgDcwjTkBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MsgDcwjTk> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getType()), MsgDcwjTk::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getMust()), MsgDcwjTk::getMust, bo.getMust());
        lqw.like(StringUtils.isNotBlank(bo.getTopic()), MsgDcwjTk::getTopic, bo.getTopic());
        lqw.eq(StringUtils.isNotBlank(bo.getFormat()), MsgDcwjTk::getFormat, bo.getFormat());
        return lqw;
    }

    /**
     * 新增题库管理
     */
    @Override
    public Boolean insertByBo(MsgDcwjTkBo bo) {
        MsgDcwjTk add = BeanUtil.toBean(bo, MsgDcwjTk.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改题库管理
     */
    @Override
    public Boolean updateByBo(MsgDcwjTkBo bo) {
        MsgDcwjTk update = BeanUtil.toBean(bo, MsgDcwjTk.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MsgDcwjTk entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除题库管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

}
